<?php

namespace Frieza\Modules\Creators\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Creator\AdmCreatorCoupon;
use Doraemon\model\Position\BottomNav;
use Doraemon\model\Position\PositionRules;
use Doraemon\service\position\AdmOperationModule;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Filter;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class CreatorCouponController extends Controller
{
    public function list(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", 200);
//        $page = $request->input("page", 1);
//        $search['status'] = $request->input('status');

        $where = $this->buildWhere();
        $total = 200;
//        $where['LIMIT'] = [
//            ($page - 1) * $pageSize,
//            $pageSize
//        ];
        $couponsEndFalse = AdmCreatorCoupon::selectByWhere($where);
        $where = $this->buildWhere([], true);
        $couponsEndTrue = AdmCreatorCoupon::selectByWhere($where);
        $coupons = array_merge($couponsEndFalse, $couponsEndTrue);
        if ($coupons) {
            //用户分群
            $list = array_column($coupons, 'id');
            $userProfiles = AdmOperationModule::getPositionRulesById($list, PositionRules::MODULE_TYPE_CREATORS_COUPON);

            foreach ($coupons as $key => $coupon) {
                $coupons[$key]['user_profile'] = $userProfiles[$coupon['id']];
                $coupons[$key]['status'] = $coupon['end_time'] > time() ? '正常' : '失效';
                $coupons[$key]['icon'] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $coupon['icon'], ImgUrl::IMAGE_SIZE_OP_ORI);
                $link = '';
                if ($coupon['link']) {
                    $linkArr = json_decode($coupon['link'], true);
                    $link = $linkArr['link_type'] . $linkArr['link_params']['url'];
                }
                $coupons[$key]['link'] = $link;
                $coupons[$key]['start_time'] = date('Y-m-d H:i', $coupon['start_time']);
                $coupons[$key]['end_time'] = date('Y-m-d H:i', $coupon['end_time']);
            }
        }
        $gridModel = new pGridDataModel($coupons, $total, ['perPage' => $pageSize]);
        $gridList = Admin::grid($gridModel, function (Grid $grid) use ($gridModel) {
            $grid->paginate($gridModel->getPerPage());
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableRowSelector();
//            $grid->filter(function (Filter $filter) {
//                $filter->disableIdFilter();
//                $filter->column(6, function (Filter $filter) {
//                    $filter->equal('status', '状态')->select([AdmCreatorCoupon::STATUS_NORMAL => '正常', AdmCreatorCoupon::STATUS_Fail => '失效']);
//                });
//                $filter->expand();
//            });

            $grid->column('id', 'ID')->sort();
            $grid->column('start_time', '生效时间');
            $grid->column('end_time', '结束时间');
            $grid->column('title', '标题');
            $grid->column('coupon_num', '优惠额度');
            $grid->column('icon', '图片地址')->image();
            $grid->column('link', '链接地址');
            $grid->column('user_profile', '分群信息')->userProfile();
            $grid->column('status', '状态');
            $grid->column('admin_id', '操作者')->display(function ($operator) {
                return Admin::user()->find($operator)->name;
            });
            $grid->actions(function ($action) {
            });
        });
        $tab = new Tab();
        $tab->add('优惠券', $gridList->render(), true);
        $content->row($tab);
        return $content
            ->header('优惠券')
            ->description(' ')
            ->breadcrumb(['text' => '优惠券']);
    }


    public function sort(Request $request): bool
    {
        $sortInfo = $request->input('sort');
        foreach ($sortInfo as $id => $sort) {
            $res = AdmCreatorCoupon::updateById(['sort' => $sort], $id);
            if ($res == false) {
                return false;
            }
        }
        return true;
    }

    public function create(Content $content)
    {
        $tab = new Tab();
        $form = new Form();
        $form->text('title', '标题')->required();
        $form->imgUpload('icon', '图标')->help('请上传 1:1，尺寸为 40x40px 的图片');
        $form->multiLinkSelect('link', '跳转链接')->required();
        $form->datetime('start_time', '上线时间')->required();
        $form->datetime('end_time', '下线时间')->required();
        $form->text('description', '描述');
        $form->text('coupon_num', '优惠额度')->default(0)->required();
        $form->text('remarks', '备注');
        $form->userProfile('user_profile', '用户分群')->generate();

        $form->action('/admin/creators/creatorcoupon/save');
        $tab->add('添加优惠券', $form, true);
        $content->header('添加优惠券')
            ->breadcrumb(
                ['text' => '优惠券', 'url' => '/creators/creatorcoupon/list'],
                ['text' => '添加优惠券',]
            )
            ->row($tab);
        return $content;
    }

    /**
     * @throws \Exception
     */
    public function save(Request $request)
    {
        $params = $request->all();
        $tmp = $this->validateParams($params);
        if ($tmp != null) {
            return $tmp;
        }

        $userProfile = $params['user_profile'];
        $params['link'] = !empty($params['link']) ? json_encode($params['link']) : '';
        $data = [
            'title' => $params['title'],
            'icon' => $params['icon'],
            'coupon_num' => $params['coupon_num'],
            'description' => $params['description'],
            'remarks' => $params['remarks'],
            'link' => $params['link'],
            'start_time' => strtotime($params['start_time']),
            'end_time' => strtotime($params['end_time']),
            'admin_id' => Admin::user()->id,
            'edittime' => time(),
            'addtime' => time(),
            'status' => AdmCreatorCoupon::STATUS_NORMAL
        ];
        $id = AdmCreatorCoupon::addRights($data);
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        if ($id) {
            //用户分群
            AdmOperationModule::addUserProfile($id, $userProfile, PositionRules::MODULE_TYPE_CREATORS_COUPON);
            return redirect('/admin/creators/creatorcoupon/list')->with(compact('success'));
        }


    }

    public function edit(Content $content, $id)
    {
        $tab = new Tab();
        $where = ['id' => $id];
        $list = AdmCreatorCoupon::get('*', $where);

        $list['link'] = json_decode($list['link'], true);
        $list['user_profile'] = AdmOperationModule::getPositionRulesById($id, PositionRules::MODULE_TYPE_CREATORS_COUPON, true);
        $list['start_time'] = date('Y-m-d H:i:s', $list['start_time']);
        $list['end_time'] = date('Y-m-d H:i:s', $list['end_time']);
        $form = new Form($list);
        $form->text('title', '标题')->help('最多输入10个字')->attribute('maxlength', '10')->required();
        $form->imgUpload('icon', '图标')->help('请上传 1:1，尺寸为 40x40px 的图片')->required();
        $form->multiLinkSelect('link', '跳转链接')->required();
        $form->datetime('start_time', '上线时间')->required();
        $form->datetime('end_time', '下线时间')->required();
        $form->text('description', '描述');
        $form->text('coupon_num', '优惠额度')->required();
        $form->text('remarks', '备注');
        $form->userProfile('user_profile', '用户分群')->generate();

        $tab->add('修改优惠券', $form, true);
        $form->action('/admin/creators/creatorcoupon/' . $id . '/update');
        $content->header('我的优惠券')
            ->breadcrumb(
                ['text' => '我的优惠券', 'url' => '/creators/creatorcoupon/list'],
                ['text' => '修改我的优惠券',]
            )
            ->row($tab);
        return $content;
    }

    private function validateParams($params)
    {
        if (empty($params['icon'])) {
            $error = new MessageBag([
                'title' => '图片不能为空'
            ]);
            return back()->withInput()->with(compact('error'));
        }
        if (empty($params['link'])) {
            $error = new MessageBag([
                'title' => '链接不能为空'
            ]);
            return back()->withInput()->with(compact('error'));
        }
        if (strlen($params['remarks']) > 150) {
            $error = new MessageBag([
                'title' => '备注太长了'
            ]);
            return back()->withInput()->with(compact('error'));
        }
        if (strlen($params['description']) > 150) {
            $error = new MessageBag([
                'title' => '描述太长了'
            ]);
            return back()->withInput()->with(compact('error'));
        }
        return null;
    }

    /**
     * @throws \Illuminate\Validation\ValidationException
     */
    public function editSave(Request $request, $id)
    {
        $params = $request->input();
        $tmp = $this->validateParams($params);
        if ($tmp != null) {
            return $tmp;
        }
        $userProfile = $params['user_profile'];
        $params['link'] = !empty($params['link']) ? json_encode($params['link']) : '';
        $data = [
            'title' => $params['title'],
            'icon' => $params['icon'],
            'coupon_num' => $params['coupon_num'],
            'description' => $params['description'],
            'remarks' => $params['remarks'],
            'link' => $params['link'],
            'start_time' => strtotime($params['start_time']),
            'end_time' => strtotime($params['end_time']),
            'admin_id' => Admin::user()->id,
            'edittime' => time(),
        ];
        if ($id) {
            $result = AdmCreatorCoupon::updateById($data, $id);
            AdmOperationModule::addUserProfile($id, $userProfile, PositionRules::MODULE_TYPE_CREATORS_COUPON);
        }
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        $error = new MessageBag([
            'title' => '操作失败'
        ]);
        if ($result) {
            return redirect('/admin/creators/creatorcoupon/list')->with(compact('success'));
        }
        return redirect('/admin/creators/creatorcoupon/list')->with(compact('error'));
    }

    public function deleteById($id)
    {
        $result = AdmCreatorCoupon::deleteById($id);
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        $error = new MessageBag([
            'title' => '操作失败'
        ]);

        if ($result) {
            return redirect('/admin/creators/creatorcoupon/list')->with(compact('success'));
        }
        return redirect('/admin/creators/creatorcoupon/list')->with(compact('error'));
    }

    private function buildWhere($search = [], $end = false)
    {
        $where = [];

        if ($search['status']) {
            $where['status'] = $search['status'];
        } else {
            $where['status'] = AdmCreatorCoupon::STATUS_NORMAL;
        }
        if ($end == false) {
            $where['end_time[>]'] = time();
        } else {
            $where['end_time[<=]'] = time();
        }
        $where['ORDER'] = ['sort' => 'ASC', 'id' => 'DESC'];
        return $where;
    }

}